<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,100分)- 文件目录大小（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>一个文件目录的数据格式为&#xff1a;目录id&#xff0c;本目录中文件大小&#xff0c;(子目录id列表&#xff09;。</p> 
<p>其中目录id全局唯一&#xff0c;取值范围[1, 200]&#xff0c;本目录中文件大小范围[1, 1000]&#xff0c;子目录id列表个数[0,10]例如 : 1 20 (2,3) 表示目录1中文件总大小是20&#xff0c;有两个子目录&#xff0c;id分别是2和3</p> 
<p>现在输入一个文件系统中所有目录信息&#xff0c;以及待查询的目录 id &#xff0c;返回这个目录和及该目录所有子目录的大小之和。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行为两个数字M&#xff0c;N&#xff0c;分别表示目录的个数和待查询的目录id,</p> 
<ul><li>1 ≤ M ≤ 100</li><li>1 ≤ N ≤ 200</li></ul> 
<p>接下来M行&#xff0c;每行为1个目录的数据&#xff1a;</p> 
<blockquote> 
 <p>目录id 本目录中文件大小 (子目录id列表)</p> 
</blockquote> 
<p>子目录列表中的子目录id以逗号分隔。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p> 待查询目录及其子目录的大小之和</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">3 1<br /> 3 15 ()<br /> 1 20 (2)<br /> 2 10 (3)</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">45</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">目录1大小为20&#xff0c;包含一个子目录2 (大小为10)&#xff0c;子目录2包含一个子目录3(大小为15)&#xff0c;总的大小为20&#43;10&#43;15&#61;45</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">4 2<br /> 4 20 ()<br /> 5 30 ()<br /> 2 10 (4,5)<br /> 1 40 ()</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">60</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">目录2包含2个子目录4和5&#xff0c;总的大小为10&#43;20&#43;30 &#61; 60</td></tr></tbody></table> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>用例1图示&#xff1a;</p> 
<p><img alt="" height="319" src="https://img-blog.csdnimg.cn/053550d404e0447bb10c4a9ca7b297e0.png" width="234" /></p> 
<p></p> 
<p>用例2图示&#xff1a;</p> 
<p><img alt="" height="238" src="https://img-blog.csdnimg.cn/ef931cd29a6545a7841fd88962d2e5dc.png" width="406" /></p> 
<p></p> 
<p>本题的目录与子目录的关系&#xff0c;可以看出是一棵树&#xff0c;而计算某个目录及其子目录的文件大小总和&#xff0c;其实就是遍历某个节点下所有分支。</p> 
<p>因此&#xff0c;本题可以使用深度优先搜索dfs来解决。下面代码中深度优先搜索&#xff0c;是基于栈实现的&#xff0c;而不是基于递归。基于栈实现dfs的好处是&#xff0c;可以避免较深递归产生的执行栈溢出。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">Java算法源码</h4> 
<pre><code class="language-java">import java.util.*;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int m &#61; sc.nextInt();
    int n &#61; sc.nextInt();

    HashMap&lt;Integer, ArrayList&lt;Integer&gt;&gt; children &#61; new HashMap&lt;&gt;();
    HashMap&lt;Integer, Integer&gt; cap &#61; new HashMap&lt;&gt;();
    for (int i &#61; 0; i &lt; m; i&#43;&#43;) {
      int fa_id &#61; sc.nextInt();
      int fa_cap &#61; sc.nextInt();

      children.putIfAbsent(fa_id, new ArrayList&lt;&gt;());
      cap.putIfAbsent(fa_id, fa_cap);

      String ch_str &#61; sc.next();
      if (ch_str.length() &gt; 2) {
        children
            .get(fa_id)
            .addAll(
                Arrays.stream(ch_str.substring(1, ch_str.length() - 1).split(&#34;,&#34;))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList()));
      }
    }

    System.out.println(getResult(children, cap, n));
  }

  public static int getResult(
      HashMap&lt;Integer, ArrayList&lt;Integer&gt;&gt; children, HashMap&lt;Integer, Integer&gt; cap, int target) {
    int ans &#61; 0;

    LinkedList&lt;Integer&gt; stack &#61; new LinkedList&lt;&gt;();
    stack.add(target);

    while (stack.size() &gt; 0) {
      Integer id &#61; stack.removeLast();
      if (!cap.containsKey(id)) continue;
      ans &#43;&#61; cap.get(id);
      stack.addAll(children.get(id));
    }

    return ans;
  }
}
</code></pre> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let m, n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61; 1) {
    [m, n] &#61; lines[0].split(&#34; &#34;).map(Number);
  }

  if (m &amp;&amp; lines.length &#61;&#61; m &#43; 1) {
    lines.shift();

    const children &#61; new Map();
    const cap &#61; new Map();

    lines.forEach((s) &#61;&gt; {
      let [fa_id, fa_cap, ch_list_str] &#61; s.split(&#34; &#34;);

      fa_id &#61; Number(fa_id);
      fa_cap &#61; Number(fa_cap);

      children.set(fa_id, []);
      cap.set(fa_id, fa_cap);

      if (ch_list_str.length &gt; 2) {
        children.get(fa_id).push(
          ...ch_list_str
            .substring(1, ch_list_str.length - 1)
            .split(&#34;,&#34;)
            .map(Number)
        );
      }
    });

    console.log(getResult(children, cap, n));
    lines.length &#61; 0;
  }
});

function getResult(children, cap, target) {
  let ans &#61; 0;

  const stack &#61; [];
  stack.push(target);

  while (stack.length &gt; 0) {
    const id &#61; stack.pop();
    if (cap.get(id) &#61;&#61;&#61; undefined) continue;
    ans &#43;&#61; cap.get(id);
    stack.push(...children.get(id));
  }

  return ans;
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
m, n &#61; map(int, input().split())

children &#61; {}
cap &#61; {}

for _ in range(m):
    fa_id, fa_cap, ch_str &#61; input().split()
    children[fa_id] &#61; []
    cap[fa_id] &#61; int(fa_cap)

    if len(ch_str) &gt; 2:
        children[fa_id].extend(ch_str[1:-1].split(&#34;,&#34;))


# 算法入口
def getResult(target):
    ans &#61; 0

    stack &#61; [target]

    while len(stack) &gt; 0:
        id &#61; stack.pop()
        if cap.get(id) is None:
            continue
        ans &#43;&#61; cap[id]
        stack.extend(children[id])

    return ans


# 算法调用
print(getResult(str(n)))
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>